package com.cloudy.impl;

import com.cloudy.ec2.request.EC2Request;
import com.cloudy.exception.AWSAccessException;
import com.cloudy.exception.EC2AccessException;
import com.cloudy.s3.response.AWSResponse;

import java.net.HttpURLConnection;
import java.net.URL;

import static com.cloudy.impl.Constants.HOST_HEADER;

public class EC2ServiceCaller {

    public Object callService(EC2Request request) throws AWSAccessException {
        String query = request.getQueryString();
        URL url;
        try {
            url = new URL("https", HOST_HEADER, -1, "/" + query);
            System.out.println(url.toString());
            HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
            httpConnection.setRequestMethod(request.getRequestMethod());
            httpConnection.setDoOutput(true);
            httpConnection.connect();
            System.out.println("Https response code is: " + httpConnection.getResponseCode());
            if (httpConnection.getResponseCode() != HttpURLConnection.HTTP_OK)
                new EC2ErrorResponseHandler().handleException(httpConnection.getErrorStream());
            SuccessHandler successHandler = request.getSuccessHandler();
            AWSResponse response = successHandler.handle(httpConnection);
            System.out.println("Response is " + response);
            return response.getResponse();
        } catch (Exception e) {
            throw new EC2AccessException(e);
        }
    }
}
